// 图片无法正常显示使用默认图片
function imgerrorfun() {
    var img = event.srcElement;
    img.src = "favicon.ico";
    img.onerror = null;
}

// 获取两个字符串的相似度
function getSimilarity(s, t) {
    if (!s || !t) {
        return 0
    }
    s = s.toLowerCase();
    t = t.toLowerCase();
    if (s === t) {
        return 100;
    }
    var l = s.length > t.length ? s.length : t.length
    var n = s.length
    var m = t.length
    var d = []
    var min = function (a, b, c) {
        return a < b ? (a < c ? a : c) : (b < c ? b : c)
    }
    var i, j, si, tj, cost
    if (n === 0) return m
    if (m === 0) return n
    for (i = 0; i <= n; i++) {
        d[i] = []
        d[i][0] = i
    }
    for (j = 0; j <= m; j++) {
        d[0][j] = j
    }
    for (i = 1; i <= n; i++) {
        si = s.charAt(i - 1)
        for (j = 1; j <= m; j++) {
            tj = t.charAt(j - 1)
            if (si === tj) {
                cost = 0
            } else {
                cost = 1
            }
            d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
        }
    }
    return (1 - d[n][m] / l) * 100
}

// 根据权值快排
function quickSort(arr) {
    if (arr.length <= 1) {
        return arr;
    }
    var pivotIndex = Math.floor(arr.length / 2);
    var pivot = arr.splice(pivotIndex, 1)[0];
    var left = [];
    var right = [];

    for (var i = 0; i < arr.length; i++) {
        if (arr[i].type >= pivot.type) {
            left.push(arr[i]);
        } else {
            right.push(arr[i]);
        }
    }
    return quickSort(left).concat([pivot], quickSort(right));
};

// 获取网页图标
function getFavicon(href) {
    var reg = new RegExp(/(\w+):\/\/([^/:]+)(:\d*)?/)
    let matchObj = href.match(reg)
    if (matchObj) {
      return matchObj[0] + '/favicon.ico'
    } else {
      return null
    }
    // return "https://api.qqsuu.cn/api/dm-get?url=" + href;
}

// 输入框特殊符号处理
function dealSpecial(string) {
    return string.replace(/\%/g, '%25').replace(/\#/g, '%23').replace(/\+/g, '%2B').replace(/\"/g, '%22').replace(/\'/g, '%27').replace(/\//g, '%2F').replace(' ', '+').replace(/\?/g, '%3F').replace(/\&/g, '%26').replace(/\=/g, '%3D');
}

// 格式化日期
function formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h=h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second=date.getSeconds();
    second=second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
}

/**
 * 优化的代码格式化方法
 * @param {string} code - 要格式化的代码
 * @param {Object} [options] - 格式化选项
 * @param {number} [options.indentSize=4] - 缩进空格数（默认4）
 * @returns {string} 格式化后的代码
 */
function formatCode(code, options = {}) {
    const defaultOptions = {
        indentSize: 1,
        maxLineLength: 80
    };
    options = { ...defaultOptions, ...options };

    let formatted = '';
    let indentLevel = 0;
    let inString = false;
    let stringChar = null;
    let inComment = false;
    let inLineComment = false;
    let inPhpTag = false;

    const getIndent = () => '\t'.repeat(indentLevel * options.indentSize);

    for (let i = 0; i < code.length; i++) {
        const char = code[i];
        const prevChar = code[i - 1];
        const nextChar = code[i + 1];

        if(char === '\t') {
            continue;
        }

        // 处理 PHP 标签
        if (char === '<' && nextChar === '?' && (code[i + 2] === 'p' || code[i + 2] === '=')) {
            inPhpTag = true;
            formatted += '<?php\n' + getIndent();
            i += code[i + 2] === 'p' ? 5 : 2; // <?php 或 <?=
            continue;
        }

        if (inPhpTag && char === '?' && nextChar === '>') {
            inPhpTag = false;
            formatted += '\n' + getIndent() + '?>';
            i++;
            continue;
        }

        // 处理字符串
        if (!inComment && !inLineComment && (char === '"' || char === "'" || char === '`')) {
            if (!inString) {
                inString = true;
                stringChar = char;
                formatted += char;
            } else if (char === stringChar) {
                // 检查是否是转义的引号
                if (prevChar !== '\\' || (prevChar === '\\' && code[i - 2] === '\\')) {
                    inString = false;
                    stringChar = null;
                    formatted += char;
                } else {
                    formatted += char;
                }
            } else {
                formatted += char;
            }
            continue;
        }

        // 处理块注释
        if (!inString && !inComment && !inLineComment && char === '/' && nextChar === '*') {
            inComment = true;
            // 如果注释不在行首，先换行
            if (formatted.length > 0 && !formatted.endsWith('\n')) {
                formatted += '\n' + getIndent();
            }
            formatted += '/*';
            i++;
            continue;
        }

        if (inComment && char === '*' && nextChar === '/') {
            inComment = false;
            formatted += '*/\n' + getIndent();
            i++;
            continue;
        }

        // 处理行注释
        if (!inString && !inComment && !inLineComment && char === '/' && nextChar === '/') {
            inLineComment = true;
            formatted += '//';
            i++;
            continue;
        }

        if (inLineComment && char === '\n') {
            inLineComment = false;
            formatted += '\n' + getIndent();
            continue;
        }

        // 如果在注释或字符串中，直接添加字符
        if (inComment || inLineComment || inString) {
            formatted += char;
            continue;
        }

        // 处理代码结构
        switch (char) {
            case '{':
                // 在 { 前添加空格（如果前面不是空格或换行）
                if (formatted.length > 0 && !/[ {\n(\[]/.test(formatted[formatted.length - 1])) {
                    formatted += ' ';
                }
                formatted += '{\n';
                indentLevel++;
                formatted += getIndent();
                break;
            case '}':
                indentLevel = Math.max(0, indentLevel - 1);
                formatted = formatted.trimEnd() + '\n' + getIndent() + '}';
                // 检查后面是否有分号或逗号
                if (nextChar === ';' || nextChar === ',') {
                    formatted += nextChar;
                    i++;
                }
                // 检查是否是数组或对象结束
                if (nextChar && /[,\n]/.test(nextChar)) {
                    formatted += nextChar;
                    i++;
                }
                formatted += '\n' + getIndent();
                break;
            case ';':
                formatted = formatted.trimEnd() + ';';
                break;
            case '(':
            case '[':
                // 处理函数调用和数组访问
                const lastChar = formatted.trimEnd().slice(-1);
                if (lastChar && !/\s/.test(lastChar) && lastChar !== '(' && lastChar !== '[') {
                    if(char === '(' && lastChar === ' ') {
                        formatted = formatted.substr(0, formatted.length - 1);
                    }
                    if(char === '[' && lastChar === '=') {
                        formatted += ' ';
                    }
                }
                formatted += char;
                break;
            case ')':
            case ']':
                formatted = formatted.trimEnd() + char;
                break;
            case ',':
                formatted = formatted.trimEnd() + ', ';
                break;
            case ':':
                // 处理三元运算符和标签
                if (nextChar && !/\s/.test(nextChar)) {
                    formatted += ': ';
                } else {
                    formatted += char;
                }
                break;
            case '\n':
            case '\r':
                // 保留原有的换行，但重新缩进
                formatted += '\n' + getIndent();
                break;
            default:
                // 处理运算符
                if (/[=+\-*/%&|^<>!?~]/.test(char)) {
                    // 特殊处理 ++ -- 和 -> 等运算符
                    if ((char === '+' && nextChar === '+') ||
                        (char === '-' && nextChar === '-') ||
                        (char === '-' && nextChar === '>')) {
                        formatted += char;
                    }
                    // 处理赋值类运算符
                    else if (char === '=' && prevChar && /[<>=!+\-*/%&|^]/.test(prevChar)) {
                        formatted += char + ' ';
                    }
                    // 其他运算符前后加空格
                    else if (!/\s/.test(prevChar) && !/\s/.test(nextChar)) {
                        formatted = formatted.trimEnd() + ' ' + char + ' ';
                    } else {
                        formatted += char;
                    }
                } else {
                    // 普通字符，直接添加
                    formatted += char;
                }
        }
        // 简单的行长度检查（可选）
        const currentLine = formatted.split('\n').pop();
        if (currentLine.length > options.maxLineLength) {
            // 在最近的运算符或逗号处换行
            const lastSpace = currentLine.lastIndexOf(' ', options.maxLineLength - 20);
            if (lastSpace > currentLine.length / 2) {
                formatted = formatted.slice(0, formatted.length - currentLine.length + lastSpace) +
                    '\n' + getIndent() +
                    currentLine.slice(lastSpace + 1);
            }
        }
    }

    // 后处理：清理多余的空格和空行
    formatted = formatted
        .replace(/ +/g, ' ') // 合并多个空格
        .replace(/ \n/g, '\n') // 移除行尾空格
        .replace(/\n{3,}/g, '\n\n') // 限制连续空行
        .replace(/([{};])\n\s*\n/g, '$1\n') // 结构后不要有空行
        .replace(/([)\]}])\s*\{/g, '$1 {') // 统一空格风格
        .trim();

    return formatted;
}

// 是否移动端
function isMobile() {
    const userAgentInfo = navigator.userAgent;
    const mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];
    const mobileFlag = mobileAgents.some((mobileAgent) => {
        return userAgentInfo.indexOf(mobileAgent) > 0;
    });

    return mobileFlag;
}